package trees;

import java.util.ArrayList;
import java.util.List;

public class DetectCycle {
    public static ListNode detectCycle(ListNode head) {
        List<Integer> vals = new ArrayList<>();
        if (head == null) {
            return null;
        }
        vals.add(head.val);

        while (head.next != null) {
            int nextVal = head.next.val;
            if (vals.contains(nextVal)) {
                return head;
            } else {
                head = head.next;
            }
        }

        return null;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(3);
        node.next = new ListNode(2);
        node.next.next = new ListNode(0);
        node.next.next.next.val = -4;
        node.next.next.next.next = node.next;

        DetectCycle.detectCycle(node);
    }
}
